package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @Author 鹏少
 * @Date 2023/9/19
 * @Date 11:18
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {



    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WebSocketServer webSocketServer;



    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {

        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setNumber(UUID.randomUUID().toString());
        log.info("随机生成的订单ID{}", orders.getNumber());
        orders.setStatus(orders.PENDING_PAYMENT);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(orders.UN_PAID);


        AddressBook addressBook = addressBookMapper.getById(orders.getAddressBookId());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orderMapper.insert(orders);


        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        OrderDetail orderDetail = new OrderDetail();
        list.forEach(s -> {
            BeanUtils.copyProperties(s, orderDetail, "id");
            orderDetail.setOrderId(orders.getId());
            orderDetailMapper.insert(orderDetail);

        });

        shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        orderSubmitVO.setOrderAmount(orders.getAmount());


        Map map=new HashMap();
        map.put("type",1);
        map.put("orderId",orders.getId());
        map.put("content","订单号:"+orders.getNumber());
        String  jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);



        return orderSubmitVO;
    }

    @Override
    public PageResult page(int page, int pageSize, Integer status) {
        PageHelper.startPage(page, pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);
        Page<Orders> ordersPage = orderMapper.page(ordersPageQueryDTO);
        List<OrderVO> list = new ArrayList<>();
        if (ordersPage != null || ordersPage.size() > 0) {
            for (Orders orders : ordersPage) {

                Long id = orders.getId();
                List<OrderDetail> orderDetailList = orderDetailMapper.selectById(id);
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetailList);
                list.add(orderVO);


            }


        }

        return new PageResult(ordersPage.getTotal(), list);

    }

    @Override
    public OrderVO selectDetail(Long id) {
        OrderVO orderVO = new OrderVO();
        Orders orders = orderMapper.selectById(id);
        List<OrderDetail> orderDetail = orderDetailMapper.selectById(orders.getId());
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetail);
        return orderVO;
    }

    @Override
    public void cancel(Long id) {
        Orders orders = orderMapper.selectById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        if (orders.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        if (orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {

            log.info("退款");
            orders.setPayStatus(Orders.REFUND);

        }
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);

    }

    @Override
    public void repetition(Long id) {

        List<OrderDetail> orderDetailList = orderDetailMapper.selectById(id);

        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart, "id");
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCartMapper.insert(shoppingCart);

        }


    }
    private static int i=0;
    @Override
    public PageResult conditionPage(OrdersPageQueryDTO ordersPageQueryDTO) {
        //做分页查询
        int page = ordersPageQueryDTO.getPage();
        int pageSize = ordersPageQueryDTO.getPageSize();
        PageHelper.startPage(page, pageSize);
        //进行查询
        Page<Orders> ordersPage = orderMapper.page(ordersPageQueryDTO);

        //创建一个集合接收订单菜品信息
        List<String> orderDishs = new ArrayList<>();

        //获取订单菜品信息 进行字符串拼接
        for (Orders orders : ordersPage) {
            List<OrderDetail> orderDetailList = orderDetailMapper.selectById(orders.getId());

            String orderDish = "";
            for (OrderDetail orderDetail : orderDetailList) {
                orderDish += orderDetail.getName() + "*" + orderDetail.getNumber() + ";";

            }
            orderDishs.add(orderDish);

        }
        //创建需要返回的集合
        List<OrderVO> list = new ArrayList<>();
        for (Orders orders : ordersPage) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            orderVO.setOrderDishes(orderDishs.get(i));
            i++;
            list.add(orderVO);

        }
        i=0;
        return new PageResult(ordersPage.getTotal(), list);
    }

    /*
    * confirmed	integer  	必须		待派送数量


      deliveryInProgress	integer	必须		派送中数量


      toBeConfirmed	     integer	必须		待接单数量
   * 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消

*/
    @Override
    public OrderStatisticsVO statistics() {

        Integer toBeConfirmed=orderMapper.statusCount(Orders.TO_BE_CONFIRMED);
        Integer deliveryInProgress=orderMapper.statusCount(Orders.DELIVERY_IN_PROGRESS);
        Integer confirmed=orderMapper.statusCount(Orders.CONFIRMED);

        OrderStatisticsVO orderStatisticsVO=new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        return orderStatisticsVO;
    }

    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO ) {
        ordersConfirmDTO.setStatus(Orders.CONFIRMED);
        orderMapper.confirm(ordersConfirmDTO);

    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {


        Orders ordersById = orderMapper.selectById(ordersRejectionDTO.getId());

        if (!ordersById.getStatus().equals(Orders.TO_BE_CONFIRMED)||ordersById==null){


            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);

        }
        if (ordersById.getPayStatus().equals(Orders.PAID)){
            log.info("退款");
        }

        Orders orders=new Orders();

        orders.setId(ordersRejectionDTO.getId());
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders);
    }

    @Override
    public void adminCancel(OrdersCancelDTO ordersCancelDTO) {

        Orders orders = orderMapper.selectById(ordersCancelDTO.getId());

        if (orders.getPayStatus().equals(Orders.PAID)){
            log.info("取消订单,需要退款");
        }
        Orders orders1=new Orders();
        orders1.setId(ordersCancelDTO.getId());
        orders1.setStatus(Orders.CANCELLED);
        orders1.setCancelTime(LocalDateTime.now());
        orders1.setCancelReason(ordersCancelDTO.getCancelReason());
        orderMapper.update(orders1);


    }

    @Override
    public void delivery(Long id) {

        Orders orders = orderMapper.selectById(id);
        if (orders==null||!orders.getStatus().equals(Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);

        }
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);



    }

    @Override
    public void complete(Long id) {
        Orders orders = orderMapper.selectById(id);
        if (orders==null||!orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){

            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);


    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param orderNumber
     */
    public void paySuccess(String orderNumber) {
        log.info("支付完成 orderNumber:{}",orderNumber);
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(orderNumber, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    @Override
    public void reminder( Long id) {

        Orders orders = orderMapper.selectById(id);
        if (orders==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        Map map=new HashMap();
        map.put("type",2);
        map.put("orderId",orders.getId());
        map.put("content","订单号:"+orders.getNumber());
        String  jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);

    }


}
